/*
 * Copyright ©
 * #
 * @author: zw
 * @date: 2021-09-05
 */

import {
  defineComponent,
  getCurrentInstance,
  onBeforeUnmount,
  onMounted,
  reactive,
  provide,
} from "vue";
import Doc from "./Dot";
import Director from "./Director";
import "./css/Carousel.scss";
export default defineComponent({
  name: "Carousel",
  components: { Doc, Director },
  props: {
    autoplay: { type: Boolean, default: true },
    deration: { type: Number, default: 3000 },
    initial: { type: Number, default: 0 },
    hasDot: { type: Boolean, default: true },
    hasDirector: { type: Boolean, default: true },
    dotBgColor: { type: String, default: '#ff5000' }
  },
  setup(props, { emit, slots }) {
    const instace = getCurrentInstance();
    const state = reactive({
      currentIndex: props.initial,
      itemLength: 0,
    });
    function getCurrentIndex() {
      return state.currentIndex;
    }
    let t = null;
    function autoPlay() {
      if (props.autoplay) {
        t = setInterval(() => {
          setIndex("next");
        }, props.deration);
      }
    }
    function setIndex(dir) {
      switch (dir) {
        case "next":
          state.currentIndex += 1;
          if (state.currentIndex === state.itemLength) {
            state.currentIndex = 0;
          }
          break;
        case "prev":
          state.currentIndex -= 1;
          if (state.currentIndex === -1) {
            state.currentIndex = state.itemLength - 1;
          }
          break;
        default:
          break;
      }
    }
    function DotClick(index) {
      state.currentIndex = index;
    }
    function mouseEnter() {
      _clearInter();
    };
    function mouseLeave() {
      autoPlay();
    }
    function _clearInter() {
      clearInterval(t);
      t = null;
    };
    function DirClick(dir) {
      setIndex(dir);
    };
    onMounted(autoPlay);
    provide("ctx", { getCurrentIndex });
    onMounted(
      () => (state.itemLength = instace.slots.default()[0].children.length)
    );
    onBeforeUnmount(_clearInter);
    return () => {
      return (
        <div class="carousel"
          onmouseenter={mouseEnter}
          onmouseleave={mouseLeave}
        >
          <div class="inner">
            {slots.default?.()}
            <Director
              dir='prev'
              hasDirector={props.hasDirector}
              onDirClick={DirClick}
            />
            <Director
              dir='next'
              hasDirector={props.hasDirector}
              onDirClick={DirClick}
            />
            <Doc
              currentIndex={state.currentIndex}
              itemLength={state.itemLength}
              hasDot={props.hasDot}
              dotBgColor={props.dotBgColor}
              onDotClick={DotClick}
            ></Doc>
          </div>
        </div>
      );
    };
  },
});
